//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    footImage: '../img/gray.png',
    weight: 0
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    
  },
  //开始称重
  startWeigh: function () {
    let that = this;
    wx.openBluetoothAdapter({
      success(res) {

        setInterval(function () {
          //开始搜寻附近的蓝牙外围设备。
          wx.startBluetoothDevicesDiscovery({
            success(res) {

              wx.onBluetoothDeviceFound(function (res) {
                var devices = res.devices;
                var param = that.ab2hex(devices[0].advertisData);
                //广播前14位、红色部分(FFFF3003030733)则表示是美乐健康的体脂称发出的广播
                if (param.substring(0, 14) == "ffff3003030733") {
                  that.setData({
                    footImage: "../img/green.png"
                  })
                  //广播27-28位、蓝色部分(A0)、如果是AA或者BB的话、表示当前广播是锁定后的最终广播、最终体重 
                  console.log(param.substring(26, 28));
                  if (param.substring(26, 28) == "aa" || param.substring(26, 28) == "bb"){
                    wx.showToast({
                      title: '称重结束',
                      icon: 'none',
                      duration: 1500
                    })
                  }
                  //计算体重
                  let num = that.ex16hex(param.substring(31, 38));
                  console.log(param.substring(28, 30));
                  if (param.substring(28, 30) == "01"){
                    that.setData({
                      weight: num/10 + "kg"
                    })
                  }else{
                    that.setData({
                      weight: num + "斤"
                    })
                  }
                  //广播39-42位、紫色部分(0000)是阻抗值、十六进制、0000代表没有光脚称重。暂时不做处理
                  if (param.substring(39, 42) == "0000") {
                    
                  }
                }
              })

            }
          })
        }, 1000)

      },
      fail(err) {
        console.log(err);
      }
    })
  },
  ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },
  ex16hex: function(hex) {
    var len = hex.length;
    var a = new Array(len);
    var code;
    for(var i = 0; i<len; i++) {
      code = hex.charCodeAt(i);
      if (48 <= code && code < 58) {
        code -= 48;
      } else {
        code = (code & 0xdf) - 65 + 10;
      }
      a[i] = code;
    }

    return a.reduce(function (acc, c) {
      acc = 16 * acc + c;
      return acc;
    }, 0);
  }
})
